<script setup>
  import { ref, onMounted } from 'vue'
  import { VueFlow, useVueFlow } from '@vue-flow/core'

  const { addEdges, removeEdges, updateEdgeData } = useVueFlow()
  const instance = useVueFlow()
  const nodes = ref([
    {
      id: '1',
      position: { x: 50, y: 50 },
      data: { label: 'Node 1' },
    },
    {
      id: '2',
      position: { x: 50, y: 250 },
      data: { label: 'Node 2' },
    },
    {
      id: '3',
      position: { x: 50, y: 450 },
      data: { label: 'Node 3' },
      type: 'input',
    },
    {
      id: '4',
      type: 'output',
      position: { x: 50, y: 650 },
      data: { label: 'Node 4' },
    },
  ])

  const edges = ref([
    {
      id: 'e1->2',
      source: '1',
      target: '2',
      label: '哈哈',
      type: 'smoothstep',
    },
  ])

  const nodesDraggable = ref(true)
  const nodesConnectable = ref(true)

  const onAddNode = () => {
    addEdges([
      {
        id: 'e2->3',
        source: '2',
        target: '3',
        type: 'step',
        // if a node has multiple handles of the same type,
        // you should specify which handle to use by id
        sourceHandle: null,
        targetHandle: null,
      },
    ])

    edges.value.push({
      id: 'e3->4',
      source: '3',
      target: '4',
    })
  }
  const onMinusNode = () => {
    removeEdges(['e2->3'])

    // edges.value = edges.value.filter((edge) => edge.id !== 'e1->2')
  }

  const onUpdateNode = () => {
    // updateEdgeData('e2->3', { target: '4' })
    updateEdgeData('e2->3', { hello: 'mona' })
    updateEdgeData('e1->2', { name: 'zby' })

    const edge = instance.findEdge('e3->4')
    edge.animated = !edge.animated
    edge.type = 'straight'

    console.log(instance, instance.getEdges)
  }

  const onChangeProps = () => {
    nodesDraggable.value = !nodesDraggable.value
    nodesConnectable.value = !nodesConnectable.value
  }
</script>

<template>
  <div class="w-full h-full">
    <button @click="onAddNode">Add Edge</button> |
    <button @click="onMinusNode">Minus Edge</button> |
    <button @click="onUpdateNode">Update Edge</button> |
    <button @click="onChangeProps">change</button> |
    <VueFlow
      auto-connect
      :default-viewport="{ zoom: 1 }"
      :max-zoom="4"
      :min-zoom="0.8"
      :nodes="nodes"
      :edges="edges"
      :nodes-draggable="nodesDraggable"
      :nodes-connectable="nodesConnectable"
      @edge-click="console.log('edge clicked', $event)"
    />
  </div>
</template>
